package org.idea.qiyu.common;

/**
 * @Author linhao
 * @Date created in 11:31 上午 2021/10/24
 */
public class ByteConvertUtils {

    /**
     * 字节转成数字 int 大小是4个字节
     *
     * @param bytes
     * @return
     */
    public static int byteToInt(byte[] bytes) {
        if (bytes.length != 4) {
            return 0;
        }
        return (bytes[0]) & 0xff | (bytes[1] << 8) & 0xff00 | (bytes[2] << 16) & 0xff0000 | (bytes[3] << 24) & 0xff000000;
    }

    /**
     * 数字转成字节 int 大小是4个字节
     *
     * @param n
     * @return
     */
    public static byte[] intToByte(int n) {
        byte[] buf = new byte[4];
        for (int i = 0; i < buf.length; i++) {
            buf[i] = (byte) (n >> (8 * i));
        }
        return buf;
    }

    public static void main(String[] args) {
//        byte[] bytes = ByteConvertUtils.intToByte(123128);
//        int r = ByteConvertUtils.byteToInt(bytes);
//        System.out.println(r);
//        for (byte aByte : bytes) {
//            System.out.println(aByte);
//        }

        int result = ByteConvertUtils.byteToInt(new byte[]{127,127});
        System.out.println(result);
    }
}
